import render_helper from "./render_helper.mjs";
import thin_render from "./thin_render.mjs";
import datarover from "./datarover.mjs";
import { confirm } from "./dialog.mjs";
import { thin } from "../thin3.mjs";

export default function formview_template(container, template) {
  let formview = document.createElement("formview");
  container.appendChild(formview);
  formview.thin_viewmode = template.mode || "read";
  let data = template.data || datarover(container, template.datapath);
  if (data) formview.thin_data = data;
  render_helper(formview, template);
  formview.thin_render = function () {
    thin(formview).empty();
    thin_render(formview, template.formview);
    // console.log({ template });
    if (template.onsave || template.oninsert || template.ondelete) {
      thin_render(formview, {
        block: [
          {
            button: "delete",
            click: (e) => {
              confirm("是否确认删除?").confirmed((d) => {
                if (template.ondelete) template.ondelete(e);
              });
            },
            when: typeof template.ondelete === "function",
          },
          {
            button: "edit",
            click: (e) => {
              e.editmode();
            },
            when: typeof template.onsave === "function",
          },
        ],
        insert: [
          {
            button: "cancel",
            click: (e) => {
              confirm("是否放弃保存数据？")
                .confirmed((data) => {
                  if (template.oncancel) template.oncancel(e);
                })
                .cancelled(() => {
                  e.done();
                });
            },
          },
          {
            button: "add",
            click: (e) => {
              confirm("是否保存数据")
                .confirmed(() => {
                  if (template.oninsert) template.oninsert(e);
                  else template.onsave(e);
                })
                .cancelled(() => {
                  e.done();
                });
              // if (confirm("是否保存数据?")) {
              //   if (template.oninsert) template.oninsert(e);
              //   else template.onsave(e);
              // }
            },
          },
        ],
        edit: [
          {
            button: "cancel",
            click: (e) => {
              e.readmode();
            },
          },
          {
            button: "save",
            click: (e) => {
              confirm("是否保存数据?")
                .confirmed((d) => {
                  template.onsave(e);
                })
                .cancelled((d) => {
                  e.done();
                });
              // if (confirm("是否保存数据?")) {
              //   template.onsave(e);
              // }
            },
          },
        ],
      });
    }
  };
  formview.thin_render();
}
